using System.Collections.Generic;
using System.Linq;
using DG.Tweening;
using UnityEngine;


/// <summary>
/// 槽子数据
/// </summary>
public class SlotsData {
    private List<Transform> slotGameObjList = new List<Transform>();

    /// <summary>
    /// 待消除队列
    /// </summary>
    /// <returns></returns>
    private List<List<Transform>> waitClearList = new List<List<Transform>>();

    private List<Vector3> slotsTargetList = new List<Vector3>();

    private bool isDirty = false;

    public bool IsDirty {
        get {
            return isDirty;
        }
        set {
            isDirty = value;
            if(value) {
                
            }
        }
    }
    
    /// <summary>
    /// 更新所有的槽位
    /// </summary>
    private void UpdateAllSlots()
    {
        // 赛选掉被标记清除的元素
        slotGameObjList = slotGameObjList.Where((obj) => obj != null && !obj.GetComponent<Toy>().TagClear).ToList();
        Debug.Log($"刷新槽子里面所有物体的位置 {slotGameObjList.Count}");

        for (int i = 0; i < slotGameObjList.Count; i++)
        {
            Transform item = slotGameObjList[i];
            Toy toyItem = item.GetComponent<Toy>();
            if (toyItem == null || toyItem.TagClear)
            {
                continue;
            }
            float targetX = slotsTargetList[i].x;

            if (!toyItem.TagClear)
            {
                item.DOMoveX(targetX, 0.1f);
                toyItem.SlotIndex = i;
            }
        }
        IsDirty = false;
    }

    /// <summary>
    /// 从起始槽位往后更新位置而不是全部更新
    /// </summary>
    /// <param name="startIndex"></param>
    private void UpdateRemainSlots(int startIndex) {
        for(int i = startIndex; i < slotGameObjList.Count; i++) {
            Transform slotItem = slotGameObjList[i];
            Toy toyItme = slotItem.GetComponent<Toy>();
            if(toyItme.TagClear || toyItme == null) continue;
            float targetX = slotsTargetList[i].x;
            toyItme.SlotIndex = i;
            slotItem.DOMoveX(targetX,0.1f);
        }
    }

    /// <summary>
    /// 找出最后一个和传入类型相同的物体索引
    /// </summary>
    /// <param name="trs"></param>
    /// <returns></returns>
    public int FindLastSameTypeObject(Transform trs)
    {
        int right = slotGameObjList.Count - 1;

        while (right >= 0)
        {
            if (slotGameObjList[right] == null)
            {
                Debug.Log($"{right}位置上的物体为空");
                continue;
            }
            if (slotGameObjList[right].name == trs.name)
            {
                return right;
            }
            right--;
        }
        return right;
    }
    
}